package com.nanyang.tms.controller.company;

import com.nanyang.common.core.annotation.BindParam;
import com.nanyang.common.core.dict.CommonEnum;
import com.nanyang.common.core.domain.ApiResult;
import com.nanyang.common.core.exception.ServiceException;
import com.nanyang.common.core.page.PageBean;
import com.nanyang.tms.api.dto.request.company.CompanyAddRequest;
import com.nanyang.tms.api.dto.request.companyrecharge.CompanyRechargeAddRequest;
import com.nanyang.tms.api.dto.request.companyrecharge.CompanyRechargeQueryRequest;
import com.nanyang.tms.api.dto.request.companysender.CompanySenderAddRequest;
import com.nanyang.tms.api.dto.response.companyrecharge.CompanyRechargePageResponse;
import com.nanyang.tms.api.dto.response.companyrecharge.RechargeAddResponse;
import com.nanyang.tms.api.service.companyrecharge.CompanyRechargeRpcService;
import com.nanyang.tms.common.contstant.TmsCommonConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/recharge")
public class CompanyRechargeController {

    @Reference(version = "1.0.0", timeout = 10000, check = false)
    private CompanyRechargeRpcService companyRechargeRpcService;

    /**
     * <p>listCompanyRecharge</p>
     * <p>Description:查询列表</p>
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @BindParam
    public ApiResult<PageBean<CompanyRechargePageResponse>> listCompanyRecharge(@BindParam @RequestBody CompanyRechargeQueryRequest param) {
        ApiResult<PageBean<CompanyRechargePageResponse>> apiResult = companyRechargeRpcService.listCompanyRecharge(param);
        if (apiResult.getCode() == CommonEnum.SYSTEM_EXCEPTION.getCode()) {
            throw new ServiceException(CommonEnum.SYSTEM_EXCEPTION.getCode(), apiResult.getMessage());
        }
        return apiResult;
    }

    /**
     * 下单
     * @param param
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @BindParam
    public ApiResult<RechargeAddResponse> save(@BindParam @RequestBody @Valid CompanyRechargeAddRequest param) {
        ApiResult<RechargeAddResponse> apiResult = companyRechargeRpcService.save(param);
        if (apiResult.getCode() == CommonEnum.SYSTEM_EXCEPTION.getCode()) {
            throw new ServiceException(CommonEnum.SYSTEM_EXCEPTION.getCode(), apiResult.getMessage());
        }
        return apiResult;
    }

    /**
     * 查询订单支付状态
     */
    @RequestMapping(value = "/queryOrderState/{orderCode}", method = RequestMethod.GET)
    public ApiResult<Integer> queryOrderState(@PathVariable(value = "orderCode") String orderCode) {
        ApiResult<Integer> apiResult = companyRechargeRpcService.queryOrderState(orderCode);
        if (apiResult.getCode() == CommonEnum.SYSTEM_EXCEPTION.getCode()) {
            throw new ServiceException(CommonEnum.SYSTEM_EXCEPTION.getCode(), apiResult.getMessage());
        }
        return apiResult;
    }
    /**
     * 支付宝扫码支付callBack
     */
    @RequestMapping(value = "/scanAliPayCallBack", method = RequestMethod.POST)
    public String scanAliPayCallBack(HttpServletRequest request) {
        log.info("支付宝回调了一次");
        ApiResult<Boolean> apiResult = companyRechargeRpcService.scanAliPayCallBack(getAlipayRequest(request));
        if (apiResult.getCode() == CommonEnum.SYSTEM_EXCEPTION.getCode()) {
            throw new ServiceException(CommonEnum.SYSTEM_EXCEPTION.getCode(), apiResult.getMessage());
        }
        return TmsCommonConsts.SUCCESS;
    }

    /**
     * 获取支付宝支付完成参数
     */
    private Map<String, String> getAlipayRequest(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes(), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        return params;
    }
}
